package com.wzx.mvc.interceptor;


import com.wzx.mvc.annocation.Security;
import com.wzx.mvc.controller.UserController;
import com.wzx.mvc.core.HandlerInterceptor;
import com.wzx.mvc.core.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Map;
import java.util.Optional;

public class SecurityInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HandlerMethod hm = (HandlerMethod) handler;

        response.setCharacterEncoding("utf-8");

        Security annotation = Optional
                .ofNullable(hm.getControllerOrigin().getClass().getAnnotation(Security.class))
                .orElse(hm.getMethod().getAnnotation(Security.class));
        if (annotation == null) {
            return true;
        }
        String username = request.getParameter("username");
        if (Arrays.asList(annotation.value()).stream().anyMatch(item -> item.equals(username))) {
            return true;
        }

        PrintWriter writer = response.getWriter();
        writer.println("没有权限");
        writer.println("可以用账号如下:");
        for (String allowUsername : annotation.value()) {
            writer.println(allowUsername);
        }
        return false;
    }
}
